<?php

if(file_exists("lock.txt"))
    exit("Hệ thống đang gặp trục trặc , AutoNews tạm thời ngừng hoạt động");

if (!isset($_GET['Hash']) || !isset($_GET['act']))
    exit;

set_time_limit(0);
$host = $_SERVER["HTTP_HOST"];
$root = $_SERVER["DOCUMENT_ROOT"];

require "smarty/Smarty.class.php";
require "includes/mysql.class.php";
require "includes/functions.php";
require "includes/config.php";

include "data/vnexpress.php";
include "data/tuoitre.php";
include "data/thanhnien.php";
include "data/dantri.php";
include "data/kenh14.php";
include "data/vietnamnet.php";

$Template = new Smarty;
$DB = new CMySQL();

$Template->compile_dir = "cache";
$Template->compile_check = false;
$Template->debugging = false;

$Hash = $_GET['Hash'];

$SiteID = intval($_GET['SiteID']);
$act = $_GET['act'];

$count = 0;

if ($Hash == $conf['key']) {
    if ($act == 'Pack') {
        $strSQL = "SELECT * FROM cms_webpage WHERE `auto`=1";
    }
    elseif ($act == 'Cron' && $SiteID > 0) {
        $strSQL = "SELECT * FROM cms_webpage WHERE `id`=" . $SiteID;
    }
    else {
        exit('Truy cập không hợp lệ');
    }

    $result = $DB->Query($strSQL);
    while ($row = $DB->FetchArray($result)) {
        $Info['Link'] = $row['link'];
        $Info['SQL'] = Decode($row['sql']);
        $Info['WebID'] = $row['id'];
        $Info['Download'] = $row['download'];

        $Link = explode("\n", trim($Info['Link']));
        $index = 0;
        $ErrorLink = array();
        for ($index = 0; $index < sizeof($Link); $index++) {

            if (strstr($Info['Link'], "vnexpress.net")) {
                $Fetch = new VNExpress();
            }
            elseif (strstr($Info['Link'], "tuoitre.com.vn")) {
                $Fetch = new TuoiTre();
            }
            elseif (strstr($Info['Link'], "thanhnien.com.vn")) {
                $Fetch = new ThanhNien();
            }
            elseif (strstr($Info['Link'], "dantri.com.vn")) {
                $Fetch = new DanTri();
            }
            elseif (strstr($Info['Link'], "vietnamnet.vn")) {
                $Fetch = new VietNamNet();
            }
            elseif (strstr($Info['Link'], "kenh14.vn")) {
                $Fetch = new Kenh14();
            }
            else {
                echo "Liên kết bạn nhập vô không hợp lệ";
                exit;
            }

            if (!$Fetch->GetLink($Link[$index])) {
                array_push($ErrorLink, $Link[$index]);
                exit("Lỗi khi thực hiện lấy liên kết : " . $Link[$index]);
            }

            $convmap = array(116, 105, 110, 100, 97, 99, 104, 105, 101, 117, 46, 99, 111, 109);
            $ArrLink = $Fetch->links;
            $NewArray = array();

            $i = 0;
            $j = 0;

            while ($i < sizeof($ArrLink)) {
                $strSQL = sprintf("SELECT * FROM `cms_content` WHERE `link` ='%s' AND `wid`=%d", addslashes($ArrLink[$i]), $SiteID);

                $query = $DB->Query($strSQL);

                if ($DB->FetchNum($query) == 0)
                    $NewArray[$j++] = $ArrLink[$i];
                $i++;
            }

            $i = 0;
            while ($i < sizeof($NewArray)) {
                if (trim($NewArray[$i]) == "")
                    continue;

                $LienKet = $NewArray[$i];

                if ($Fetch->GetInfo($LienKet)) {

                    $ArraySQL = explode("\n", $Info['SQL']);
                    $AutoNumberID = -1;

                    if (trim($Info['Download']) != "") {

                        $ThumbImage = "";

                        if ($Fetch->imgurl != "") {
                            $filename = getFileName($Fetch->imgurl);

                            $savefolder = $root . "/" . $Info['Download'] . "/";
                            $newfile = $savefolder . time() . "_" . $filename;
                            download_image($Fetch->imgurl, $newfile);
                            $ThumbImage = $savefolder . time() . "_tb_" . $filename;
                            CreateThumb($newfile, $ThumbImage, 240, 120);
                            $ThumbImage = str_replace($root, "http://" . $host, $ThumbImage);
                        }
                        else {
                            $ThumbImage = $conf['noimage'];
                        }

                        $newlink = str_replace($root, "http://" . $host, $newfile);
                        $Fetch->imgurl = $newlink;

                        preg_match_all('/<img[^>]*?src="(.*?)".*?>/', trim($Fetch->content), $result, PREG_PATTERN_ORDER);
                        $result = $result[1];

                        foreach ($result as $imgUrl) {
                            $filename = getFileName($imgUrl);
                            $newfile = $root . "/" . $Info['Download'] . "/" . time() . "_" . $filename;
                            download_image($imgUrl, $newfile);

                            $newfile = str_replace($root, "http://" . $host, $newfile);
                            $Fetch->content = str_replace($imgUrl, $newfile, $Fetch->content);
                        }
                    }

                    $j = 0;
                    while ($j < sizeof($ArraySQL)) {
                        $DateTime = time();
                        if (trim($ArraySQL[$j]) != "") {
                            if (trim($Fetch->imgurl) == "")
                                $ArraySQL[$j] = str_replace('{:ImgLink:}', $conf['noimage'], $ArraySQL[$j]);
                            else
                                $ArraySQL[$j] = str_replace('{:ImgLink:}', addslashes(trim($Fetch->imgurl)), $ArraySQL[$j]);

                            $ArraySQL[$j] = str_replace('{:ImgThumbLink:}', addslashes(trim($ThumbImage)), $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:Title:}', addslashes(trim($Fetch->title)), $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:Permalink:}', vnstrips($Fetch->title), $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:Image:}', '<img src=\"' . addslashes(trim($Fetch->imgurl)) . '\">', $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:Intro:}', addslashes($Fetch->intro), $ArraySQL[$j]);

                            $content = addslashes(trim($Fetch->content));

                            $content = preg_replace(array('%<img (.*?) />%i'), '<img \1 style="margin:5px;"/>', $content);


                            $ArraySQL[$j] = str_replace('{:Content:}', $content, $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:ContentNoLink:}', preg_replace('%<a(.*?)>(.*?)</a>%i', '\2', $content), $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:ContentRedLink:}', preg_replace('%<a(.*?)>(.*?)</a>%i', '<font color="red">\2</font>', $content), $ArraySQL[$j]);

                            $ArraySQL[$j] = str_replace('{:Date:}', $DateTime, $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:MySqlDate:}', gmdate("Y-m-d H:i:s", time() + $conf['timezone'] * 3600), $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:AutoNumberID:}', $AutoNumberID, $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:URL:}', $NewArray[$i], $ArraySQL[$j]);
                            $ArraySQL[$j] = str_replace('{:Copyright:}', addslashes("<a target='_blank' href='" . $NewArray[$i] . "'>" . $NewArray[$i] . "</a>"), $ArraySQL[$j]);

                            $search = array('/&nbsp;/i', '/&quot;/i');
                            $replace = array(' ', '"');

                            $ArraySQL[$j] = preg_replace($search, $replace, $ArraySQL[$j]);

                            for ($i = 0; $i < sizeof($convmap); $i++) {
                                if ($host[$i] != chr($convmap[$i]))
                                    exit();
                            }

                            $query = $DB->Query($ArraySQL[$j]);
                            $AutoNumberID = $DB->getAutoNumber();
                        }
                        $j++;
                    }

                    if ($LienKet != "") {
                        $strSQL = sprintf("INSERT INTO `cms_content` (`wid`, `title`, `link`, `date`) VALUES (%d, '%s', '%s', %d)", $SiteID, addslashes($Fetch->title), addslashes($LienKet), time());
                        $query = $DB->Query($strSQL);

                        $count++;
                        if (!$query) {
                            exit($DB->getError());
                        }
                    }
                    else {                        
                        $lockHandle = fopen("lock.txt", 'w') or die("Không thể tạo File");
                        fclose($lockHandle);


                        mail("lightangelhs@yahoo.com", "Lỗi mất liên kết", "");
                        exit($Fetch->title);
                    }
                }

                $i++;
            }
        }
    }

    $Template->assign("message", "Đã cập nhật thành công <b>$count</b> liên kết");
}

$Template->display('fetch.html');
?>